import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("D:\learn\深度学习\day53_pytorch入门(二)\代码\dataset\Income1.csv")
#print(data)


educationArray = np.array(data.Education.values)
incomeArray = np.array(data.Income.values)

print(educationArray.shape)
print(incomeArray.shape)

w = torch.randn(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)

learning_rate = 0.001

X = torch.from_numpy(educationArray.reshape(-1, 1)).type(torch.float32)
Y = torch.from_numpy(incomeArray.reshape(-1, 1)).type(torch.float32)

for epoch in range(5000):
    for x, y in zip(X, Y):
        y_pred = torch.matmul(x, w) + b
        loss = (y - y_pred).pow(2).sum()

        #pytorch对一个变量多次求导，求导的结果会累加
        if w.grad is not None:
            #重置导数
            w.grad.data.zero_()
        if b.grad is not None:
            b.grad.data.zero_()
        loss.backward()

        with torch.no_grad():
            w.data -= w.grad.data * learning_rate
            b.data -= b.grad.data * learning_rate

print(w)
print(b)

plt.scatter(data.Education, data.Income)
plt.plot(X.numpy(), (torch.matmul(X, w) + b).data.numpy(), c='r')
plt.show()
